#include "Bluetooth_USART.h"
#include "Oled_I2C.h"
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "Handler_Command.h"

void process_command(const char *buf);

// 接收缓冲区
#define RX_BUFFER_SIZE 50
char rx_buffer[RX_BUFFER_SIZE];
uint8_t rx_index = 0;

void Bluetooth_HandleRecv() {
  if(LL_USART_IsActiveFlag_RXNE(USART2)) {
    char c = (char)LL_USART_ReceiveData8(USART2);
    if (rx_index < RX_BUFFER_SIZE - 1) {
      rx_buffer[rx_index++] = c;
    }
    if (c == '#') {
      rx_buffer[rx_index] = '\0';  // 结束符
      process_command(rx_buffer);
//      Bluetooth_SendString(rx_buffer);
      rx_index = 0;  // 重置缓冲
    }
    LL_USART_ClearFlag_RXNE(USART2);
  }
}

void Bluetooth_SendByte(uint16_t data) {
  while (!LL_USART_IsActiveFlag_TXE(USART2)) {}
    
  // Send the byte
  LL_USART_TransmitData8(USART2, data);
    
  // Wait until transmission complete
  while (!LL_USART_IsActiveFlag_TC(USART2)) {}
}

void Bluetooth_SendString(const char *data) {
  uint8_t i = 0;
  if (data == NULL || data[0] == '\0') return; // 空字符串或NULL直接返回
  while (data[i] != '\0') {
    Bluetooth_SendByte((uint16_t)data[i]);
    i++;
    if(i > 100) return;
  }
}

// 处理指令（解析并执行）
void process_command(const char *buf) {
  CommandExecutor_Type cmd;
  char buffer[50] = {0};
  if (buf == NULL) return;
  
  cmd = CommandExecutor_LookupCommand(buf);
  
  if (cmd == CMD_INVALID) {
    // 非指令，原样发回
    const char *str2 = " -- Not Supported\r\n";
    strncat(buffer, buf, strlen(buf));
    strncat(buffer, str2, strlen(str2));
    Bluetooth_SendString(buffer);
    return;
  }

  if (!CommandExecutor_ProcessCommand(cmd)) {
    const char *str2 = " -- Failed\r\n";
    strncat(buffer, buf, strlen(buf));
    strncat(buffer, str2, strlen(str2));
    Bluetooth_SendString(buffer);
  } else {
    const char *str2 = " -- Succeed\r\n";
    strncat(buffer, buf, strlen(buf));
    strncat(buffer, str2, strlen(str2));
    Bluetooth_SendString(buffer);
  }
}

int fputc(int ch, FILE *f){
  Bluetooth_SendByte(ch);
  return (ch);
}
